<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img src="../../../../assets/images/avatar.jpg" alt="" class="preview" v-if="!avatar"/>
      <img :src="avatar" alt="" class="preview" v-else/>

      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- 增加文本选择框 -->
        <input type="file" accept="image/*" style="display:none" ref="iptFile" @change="onChangeFile" />
        <el-button type="primary" icon="el-icon-plus" @click="$refs.iptFile.click()">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="onUploadImage">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data() {
    return {
      avatar:''
    }
  },
  methods: {
   async onUploadImage () {
     const {data:res} = await this.$http.patch('/my/update/avatar', {
       avatar:this.avatar
     })
     if (res.code !== 0) return this.$message.error(res.message)
     this.$message.success(res.message)
     this.avatar = ''
    //  调用actions中函数重新获取用户数据，刷新
    this.$store.dispatch('initUserInfo')
    },
    // 获取图片
    onChangeFile (e) {
      const fileList = e.target.files
      if (fileList.length > 0) {
        // 选择了图片
        console.log(fileList[0]);
        // 将图片转化为base64的字符串 FileReader
        const reader = new FileReader()
        // readAsDataURL将文件对象的数据读取到reader中，转化为base64的字符串
        reader.readAsDataURL(fileList[0])
        // load监听读取完成 reader.result
        reader.addEventListener('load', ()=> {
          // console.log(reader.result)
          this.avatar=reader.result

        })
      } else {
        // 没有选中图片
        // console.log('没有选中')
        this.avatar = ''
      }
    }
    // chooseImg() {
    //   // 模拟文件选择框的点击行为
    //   this.$refs.iptFile.click()
    // }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
